<template>
    <div class="w-full">
        <div class="flex mb-5">
            <a-cascader
                class="flex-1"
                :options="options"
                placeholder="请选择城市"
                expandTrigger="hover"
                v-model="city"
            />

            <a-button
                @click="handleAddClick"
                type="outline"
                class="ml-5"
                >添加</a-button
            >
        </div>
        <a-space
            v-if="tags.length"
            wrap
        >
            <a-tag
                v-for="(text, index) in tags"
                :key="text"
                closable
                @close="handleDeleteClick(index)"
            >
                {{ text }}
            </a-tag>
        </a-space>
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
const city = ref<string>('')
import { useFormItem } from '@arco-design/web-vue'

const { eventHandlers } = useFormItem()
const tags = defineModel<string[]>({ required: false, default: [] })
watch(
    tags,
    value => {
        if (!Array.isArray(value)) {
            tags.value = []
        }
    },
    { deep: true, immediate: true }
)

const options = [
    {
        value: '1',
        label: '北京',
        children: [{ value: '朝阳', label: '朝阳区' }]
    },
    {
        value: '2',
        label: '上海',
        children: [
            { value: '静安', label: '静安区' },
            { value: '徐汇', label: '徐汇区' }
        ]
    }
]
const handleAddClick = () => {
    if (!city.value || tags.value.includes(city.value)) return
    tags.value.unshift(city.value)
    city.value = ''
    eventHandlers.value?.onChange?.()
}

const handleDeleteClick = (index: number) => {
    tags.value.splice(index, 1)
    eventHandlers.value?.onChange?.()
}
</script>
